import XLSX from 'xlsx'
//导入方法
const importXlxs = (obj)=> {
  const _this = this;
  const inputDOM = this.$refs.inputer;
  // 通过DOM取文件数据
  this.file = event.currentTarget.files[0];
  const rABS = false; //是否将文件读取为二进制字符串
  const f = this.file;
  
  const reader = new FileReader();
  //if (!FileReader.prototype.readAsBinaryString) {
  FileReader.prototype.readAsBinaryString = function(f) {
    let binary = "";
    const rABS = false; //是否将文件读取为二进制字符串
    const pt = this;
    let wb; //读取完成的数据
    let outdata;
    const reader = new FileReader();
    reader.onload = function(e) {
      const bytes = new Uint8Array(reader.result);
      const length = bytes.byteLength;
      for(let i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      if(rABS) {
        wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
          type: 'base64'
        });
      } else {
        wb = XLSX.read(binary, {
        type: 'binary'
        });
      }
      outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
    }
    reader.readAsArrayBuffer(f);
  }
  if(rABS) {
    reader.readAsArrayBuffer(f);
  } else {
    reader.readAsBinaryString(f);
  }
}

/**
* 导出数据报表xlsx文件
* 已注入所有Vue实例，
* template模板里调用 $$outputXlsxFile
* 组件方法里调用 this.$outputXlsxFile
* 例：this.$outputXlsxFile([['字段1', '字段2'], [1, 2]], [{wch: 10}, {wch: 50}], '测试导出') 得到 测试导出.xlsx 文件
* 第一个参数是导出的数组对象，第二个参数是设置字段宽度，第三个参数是文件名
*/
const exportXlxs = (data, wscols, xlsxName) => {
/* convert state to workbook */
const ws = XLSX.utils.aoa_to_sheet(data)
ws['!cols'] = wscols
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, xlsxName)
/* generate file and send to client */
XLSX.writeFile(wb, xlsxName + ".xlsx")
}

export default {importXlxs,exportXlxs}
